<template>
  <OrderDetailSkeleton v-if="loading"></OrderDetailSkeleton>
  <view v-else class="viewport">
    <view class="navbar" :style="{ paddingTop: safeAreaInsets?.top + 'px' }">
      <view class="wrap">
        <navigator open-type="navigateBack" class="back icon-left"> </navigator>
        <view class="title">订单详情</view>
      </view>
    </view>
    <scroll-view class="main" scroll-y @scrolltolower="onScrollToLower">
      <view class="order-status">
        <view
          v-if="details?.orderState === orderStateEnum.DaiFuKuan"
          class="wait"
          :style="{ paddingTop: safeAreaInsets!.top + 20 + 'px' }"
        >
          <view class="status icon-clock margin">{{
            orderStateList[details?.orderState].text
          }}</view>
          <view class="price margin">
            <text class="pay"
              >应付金额：
              <text class="symbol">{{ details?.payMoney }}</text>
            </text>
            <view class="time">
              <text>支付剩余</text>
              <uni-countdown
                color="#fff"
                splitor-color="#fff"
                :second="details?.countdown"
                :show-day="false"
                :show-colon="false"
                @timeup="onTimeup"
              />
            </view>
          </view>
          <view class="pay-btn margin">
            <button class="btn" @tap="onPay">去支付</button>
          </view>
        </view>

        <view class="no-wait" v-else :style="{ paddingTop: safeAreaInsets!.top + 20 + 'px' }">
          <view class="status">{{ orderStateList[details?.orderState || 0].text }}</view>
          <view class="btns">
            <navigator class="re-btn" :url="`/pagesOrder/orderPre/orderPre?orderId=${details!.id}`"
              >再次购买</navigator
            >
            <button
              @tap="onFaHuo"
              v-if="details?.orderState === orderStateEnum.DaiFaHuo"
              class="fahuo-btn"
            >
              模拟发货
            </button>

            <button
              @tap="onConfirm"
              v-if="details?.orderState === orderStateEnum.DaiShouHuo"
              class="confirm-btn"
            >
              确认收货
            </button>
          </view>
        </view>
      </view>

      <view class="content">
        <view class="item-box" v-for="item in logisticList" :key="item.id">
          <view class="text">{{ item.text }}</view>
          <view class="time">{{ item.time }}</view>
        </view>
        <view class="address-box">
          <view class="user-box">
            <view class="user">{{ details?.receiverContact }}</view>
            <view class="contact">{{ details?.receiverMobile }}</view>
          </view>
          <view class="address">{{ details?.receiverAddress }}</view>
        </view>

        <view class="goods-wrap">
          <view class="goods-box">
            <navigator
              :url="`/pages/goods/goods?id=${item.spuId}`"
              v-for="item in details?.skus"
              :key="item.id"
              hover-class="none"
            >
              <view class="good">
                <view class="image">
                  <image class="pic" :src="item.image" mode="aspectFill"></image>
                </view>
                <view class="meta">
                  <view class="name">{{ item.name }}</view>
                  <text class="attrs">{{ item.attrsText }}</text>
                  <view class="price-count">
                    <view class="price">
                      <view class="price-pay symbol">{{
                        (Number(item.realPay) * Number(item.quantity)).toFixed(2)
                      }}</view>
                      <view class="price-old symbol">{{
                        (Number(item.curPrice) * Number(item.quantity)).toFixed(2)
                      }}</view>
                    </view>
                    <view class="count"> x{{ item.quantity }}</view>
                  </view>
                </view>
              </view>
            </navigator>
          </view>
          <view class="info">
            <view class="item">
              <text class="label">商品总价:</text>
              <text class="value">{{ details?.totalMoney }}</text>
            </view>
            <view class="item">
              <text class="label">运费:</text>
              <text class="value">{{ details?.postFee }}</text>
            </view>
            <view class="item">
              <text class="label">应付金额:</text>
              <text class="value should-pay">{{ details?.payMoney }}</text>
            </view>
          </view>
        </view>

        <view class="order-related">
          <view class="title">订单信息</view>
          <view class="item">
            <view class="label">订单编号:{{ details?.id }}</view>
            <view class="copy" @tap="onCopy(details!.id)">复制</view>
          </view>
          <view class="item">下单时间:{{ details?.createTime }}</view>
        </view>
      </view>
      <XtxGuess ref="xtxguessRef"></XtxGuess>
    </scroll-view>

    <view class="toolbar" :style="{ paddingBottom: safeAreaInsets?.bottom + 'px' }">
      <!-- 待付款 -->
      <block v-if="details?.orderState === orderStateEnum.DaiFuKuan">
        <view class="btn cancel-btn" @tap="popup?.open()">取消订单</view>
        <view class="btn pay-btn" @tap="onPay">去支付</view>
      </block>
      <!-- 待收货 -->
      <block v-else-if="details?.orderState === orderStateEnum.DaiShouHuo">
        <navigator
          class="btn re-btn"
          style="margin-right: 20rpx"
          :url="`/pagesOrder/orderPre/orderPre?orderId=${details!.id}`"
          >再次购买</navigator
        >
        <button class="btn confirm-btn" @tap="onConfirm">确认收货</button>
      </block>

      <!-- 已取消 待收货 待评价 -->
      <block v-else>
        <view
          v-if="[orderStateEnum.YiQuXiao, orderStateEnum.DaiPingJia].includes(details!.orderState)"
          class="btn delete-btn"
          @tap="onDelete"
          >删除订单</view
        >
        <view
          v-if="details?.orderState === orderStateEnum.DaiPingJia"
          class="btn pingjia-btn"
          @tap="onPingJia"
          >去评价</view
        >
        <navigator class="btn re-btn" :url="`/pagesOrder/orderPre/orderPre?orderId=${details!.id}`"
          >再次购买</navigator
        >
      </block>
    </view>

    <uni-popup ref="popup" type="bottom" background-color="#fff">
      <CancelReasonsPanel @close="popup?.close()" @confirm="onConfirmCancel"></CancelReasonsPanel>
    </uni-popup>
  </view>
</template>

<script lang="ts" setup>
import type { IOrderDetailResult, IOrderLogisticList } from '@/types/order'
import { onLoad, onReady } from '@dcloudio/uni-app'
import { ref, watch } from 'vue'
import { useGuessList } from '@/composables'
import Api from '@/services'
import CancelReasonsPanel from './components/CancelReasonsPanel.vue'
import XtxGuess from '@/components/XtxGuess.vue'
import OrderDetailSkeleton from './components/OrderDetailSkeleton.vue'
import { orderStateEnum, orderStateList } from '@/enums/constant'
// 猜你喜欢-组合式函数
const { xtxguessRef, onScrollToLower } = useGuessList()

const pages = getCurrentPages() //获取页面栈
const pageInstance = pages.at(-1) as any
const loading = ref(true)

const popup = ref<{
  open: (type?: UniHelper.UniPopupType) => void
  close: () => void
}>()
const details = ref<IOrderDetailResult>()
const logisticList = ref<IOrderLogisticList[]>()

// 获取安全距离
const { safeAreaInsets } = uni.getSystemInfoSync()

const getData = async (id: string) => {
  const res = await Api.OrderAPI.getOrderDetailById(id)
  details.value = res.result
}

onLoad(async (options) => {
  loading.value = true
  if (options?.id) {
    await getData(options.id)
  }
  loading.value = false
})

onReady(() => {
  // 页面渲染完毕，绑定动画效果
  pageInstance.animate(
    '.navbar',
    [{ backgroundColor: 'transparent' }, { backgroundColor: '#fff' }],
    1000,
    {
      scrollSource: '.main',
      startScrollOffset: 0,
      endScrollOffset: 50,
      timeRange: 1000,
    },
  )

  pageInstance.animate('.navbar .title', [{ color: 'transparent' }, { color: '#000' }], 1000, {
    scrollSource: '.main',
    startScrollOffset: 0,
    endScrollOffset: 50,
    timeRange: 1000,
  })

  pageInstance.animate('.navbar .back', [{ color: '#fff' }, { color: '#000' }], 1000, {
    scrollSource: '.main',
    startScrollOffset: 0,
    endScrollOffset: 50,
    timeRange: 1000,
  })
})

const onCopy = (id: string) => {
  uni.setClipboardData({
    data: id,
    success: () => {
      uni.showToast({
        icon: 'success',
        title: '复制成功',
      })
    },
  })
}

const onTimeup: UniHelper.UniCountdownOnTimeup = () => {
  // console.log('时间到')
  details.value!.orderState = orderStateEnum.YiQuXiao
}

const onPay = async () => {
  // if (!import.meta.env.DEV) {
  //   // 模拟支付
  //   await Api.OrderAPI.getPayWxPayMiniPayAPI({ orderId: details.value!.id })
  // } else {
  //   await Api.OrderAPI.getPayMockAPI({ orderId: details.value!.id })
  // }
  await Api.OrderAPI.getPayMockAPI({ orderId: details.value!.id })
  uni.redirectTo({
    url: `/pagesOrder/orderPay/orderPay?id=${details.value!.id}`,
  })
}

const onDelete = async () => {
  await Api.OrderAPI.deleteOrderById({ ids: [details.value!.id] })
  uni.showToast({
    icon: 'success',
    title: '删除成功',
  })
  setTimeout(() => {
    uni.navigateBack()
  }, 500)
}

const onConfirm = () => {
  console.log('confirm')
  uni.showModal({
    content: '为保障您的权益，请收到货并确认无误后，再确认收货',
    success: async (success) => {
      if (success.confirm) {
        const res = await Api.OrderAPI.putOrderConfirm(details.value!.id)
        details.value = res.result
      }
    },
  })
}

const onPingJia = () => {
  console.log('pingjia')
}
const onFaHuo = async () => {
  await Api.OrderAPI.getConsignmentByID(details.value!.id)
  uni.showToast({
    icon: 'success',
    title: '模拟发货成功',
  })
  details.value!.orderState = orderStateEnum.DaiShouHuo
}

const onConfirmCancel = async (reason: string) => {
  await Api.OrderAPI.cancelOrderById(details.value!.id, {
    cancelReason: reason,
  })
  uni.showToast({
    icon: 'success',
    title: '取消成功',
  })
  details.value!.orderState = orderStateEnum.YiQuXiao
}

watch(
  () => details.value?.orderState,
  async (val: number | undefined) => {
    const orderStates = [
      orderStateEnum.DaiShouHuo,
      orderStateEnum.DaiPingJia,
      orderStateEnum.YiWanCheng,
    ]
    if (val && orderStates.includes(val)) {
      const res = await Api.OrderAPI.getOrderLogistic(details.value!.id)
      logisticList.value = res.result.list
    }
  },
)
</script>

<style lang="scss" scoped>
@import './styles/orderDetail.scss';
</style>
